package 已经做过的笔试题;

/**
 * @Date 2024/9/25 15:00
 * @description: 多线程： 交替打印或者是按顺序打印(一定要会)
 * .
 * @Author LittleNight
 */
public class JoinTest {


    public static void main(String[] args) {
        final Object lock = new Object();
        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 26; i++) {
                synchronized (lock) {
                    System.out.print(i);
                    lock.notify();
                    try {
                        if (i < 26) lock.wait(); // 防止死锁的出现
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread t2 = new Thread(() -> {
//            for (int i = 0; i < 26; i++) {
            for (char i = 'a'; i <= 'z'; i++) {
//                char c = (char) ('a' + i);
                synchronized (lock) {
                    System.out.print(i);
                    lock.notify();
                    try {
                        if (i < 'z') lock.wait(); // wait 会释放对象锁, 所以另外一个线程就可以抢到锁了
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
//            synchronized (lock) {
//                lock.notifyAll();
//            }
        });
        // 数字在前面 先启动 t1.
        // 若是字母在前面, 先启动 t2
        t1.start();
        t2.start();


    }

    public static void main1(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println("t1 先打印");
        });

        Thread t2 = new Thread(() -> {
            try {
                t1.join();
            } catch (Exception e) {
                e.getMessage();
                System.out.println("异常信息" + e.getMessage());
            }
            System.out.println("t2 之后打印");
        });
        Thread t3 = new Thread(() -> {
            try {
                t2.join();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("t3 最后打印打印");
        });
        // 这个执行顺序无所谓
        t3.start();
        t2.start();
        t1.start();
    }

}
